<?php

namespace app\index\controller;

use app\CommonController;
use app\index\middleware\Auth;
use app\index\Validate\PayValidate;
use app\model\PayCoins;
use app\model\Payment;
use app\service\PayCoinService;
use app\service\PaymentService;
use think\exception\ValidateException;
use think\facade\Filesystem;

class Pay extends CommonController
{
    protected $middleware = [Auth::class];

    public function index()
    {
        if ($this->request->isPost()) {
            $params = $this->request->post();
            $where = [["member_id", "=", $this->request->uid]];
            if (!empty($params["status"])) {
                $where[] = ['status', '=', $params["status"]];
            }
            $paymentService = $this->app->make(PaymentService::class);
            $list = $paymentService->getListWithOutCount($where, "*", ["coin"]);
            $content = $this->fetch("pay-ajax", ["list" => $list]);
            $this->result(["data" => $content, "list" => $list]);
        } else {
            return $this->fetch("index");
        }
    }

    public function pay()
    {
        $service = $this->app->make(PayCoinService::class);
        $list = $service->getAll(
            [
                "pay_status" => PayCoins::PAY_COINS_STATUS_ACTIVE
            ],
            "id,coin_name,address,network,pay_min_num",
            "sort asc");
        $this->assign("list", $list);
        $this->assign("customer_link", h_get_customer_url());
        return $this->fetch("pay");
    }

    public function doPay()
    {
        $data = $this->request->post();
        try {
            validate(PayValidate::class)->check($data);
        } catch (ValidateException $e) {
            throw new ValidateException($e->getError());
        }
        $file = $this->request->file("pay_img");
        $extension = $file->extension();
        $savename = Filesystem::disk('public')->putFile($extension, $file);
        $payCoinService = $this->app->make(PayCoinService::class);
        $res = $payCoinService->get($data["coin_id"], ["coin_name", "pay_min_num"]);
        if (!$res) {
            $this->error("币种不存在");
        }
        if ($res->pay_min_num > $data["amount"]) {
            throw new ValidateException("最低充值金额不能小于{$res->pay_min_num}{$res->coin_name}");
        }
        $paymentService = $this->app->make(PaymentService::class);
        $ret = $paymentService->save([
            "member_id" => $this->request->uid,
            "amount" => $data["amount"],
            "coin_id" => $data["coin_id"],
            "pay_no" => h_create_order_no("P"),
            "pay_img" => Filesystem::disk('public')->url($savename),
            "status" => Payment::PAYMENT_STATUS_PENDING
        ]);
        if ($ret) {
            $this->success("充值成功");
        } else {
            $this->error("充值失败");
        }
    }
}